<?php

namespace App\Http\Controllers\Web;
use App\Models\Area;
use App\Models\Escort;
use App\Models\School;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

/**
 * 学校管理
 * Class ManageController
 * @package App\Modules\School\Http\Controllers\WEB
 */
class SchoolController extends Controller
{

    /**
     * 查找用户
     */
    public function searchSchool()
    {
        $query = $this->query;
        $callback = request()->input('callback');
        $escort_id = request()->input('escort_id');
        $escort = Escort::find($escort_id);
        $builder = School::query();
        if($query['keywords']){
            $builder->where(function($q) use($query){
                $q->where('name', 'like', "%{$query['keywords']}%");
            });
        }
        $pager = $builder->get()->toArray();
        $arr_school_ids = explode(',',$escort->school_ids);
        foreach ($pager as &$item){
            if(in_array($item['id'],$arr_school_ids)){
                $item['is_checked'] = 1;
            }
        }

        return view('escort.school_list', [
            'pager' => $pager,
            'callback' => $callback,
            'escort_id' => $escort_id,
            'query' => $query
        ]);
    }
    /**
     * 获取地址
     */
    public function area()
    {
        $area = Area::select(['id', 'name', 'pid'])->get()->toArray();
        $province = array_merge(array_filter($area, function($item){
            return $item['pid'] == 0;
        }));
        foreach ($province as &$item){
            $item['children'] = array_merge(array_filter($area, function($item1)use($item){
                return $item1['pid'] == $item['id'];
            }));
            foreach ($item['children'] as &$item2){
                $item2['children'] = array_merge(array_filter($area, function($item1)use($item2){
                    return $item1['pid'] == $item2['id'];
                }));
            }
        }
        return $this->success($province);
    }

    public function index()
    {
        $schools = School::paginate($this->pageNum);

        return view('school.index', ['pager' => $schools]);
    }

    public function create()
    {
        return view('school.create');
    }

    public function store(Request $request)
    {
        $data = $request->all();
        $model = new School();
        $model->fill($data)->save();

        return $this->success('', 'ok', route('school.index'));
    }

    public function edit(Request $request, $id)
    {
        $school = School::where('id', $id)->first();
        return view('school.edit', ['model' => $school]);
    }

    public function update(Request $request,$id)
    {
        $data = $request->all();
        $school = School::find($id);
        $school->fill($data)->save();

        return $this->success('','ok', route('school.index'));
    }
}
